<template>
    <div class="site-page">
        <!-- 顶部工具条 -->
        <div class="page-header">
            <div class="toolbar">
                <a-input v-model:value="query.keyword" allow-clear class="search-input" placeholder="输入名称或地址搜索"
                    @pressEnter="handleSearch">
                    <template #prefix>
                        <icon-search-outlined />
                    </template>
                </a-input>

                <a-button class="btn" @click="handleSearch">
                    <icon-search-outlined style="margin-right: 4px" /> 搜索
                </a-button>

                <a-button type="primary" class="btn" @click="openCreate">
                    + 新增
                </a-button>
            </div>
        </div>

        <!-- 主体卡片 -->
        <div class="card">
            <a-table :data-source="dataSource" :columns="columns" :loading="loading" :row-key="row => row.site_id"
                :pagination="false" :scroll="{ x: 980 }" size="middle" class="site-table">
                <template #bodyCell="{ column, record }">
                    <!-- 图片 -->
                    <template v-if="column.key === 'logo_s3'">
                        <div class="logo-box">
                            <a-image :src="record.logo_s3" :alt="record.site_name" :fallback="fallbackImg"
                                :preview="false" />
                        </div>
                    </template>

                    <!-- 地址 -->
                    <template v-else-if="column.key === 'home_url'">
                        <a-tooltip :title="record.home_url">
                            <span class="url-text">{{ record.home_url }}</span>
                        </a-tooltip>
                    </template>

                    <!-- 操作 -->
                    <template v-else-if="column.key === 'actions'">
                        <a-space size="small" wrap>
                            <a-button type="link" @click="openEdit(record)">编辑</a-button>
                            <a-button type="link" danger class="del-link" @click="askDelete(record)">
                                删除
                            </a-button>
                        </a-space>
                    </template>
                </template>
            </a-table>

            <!-- 分页 -->
            <div class="table-footer">
                <div class="total-text">共 {{ total }} 条</div>
                <a-pagination :current="query.page" :total="total" :page-size="query.pageSize"
                    :page-size-options="['10', '20', '30', '50']" show-size-changer show-quick-jumper
                    @change="onPageChange" @showSizeChange="onPageSizeChange" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined as IconSearchOutlined } from '@ant-design/icons-vue'
import api from '@/api'

/* ======================== 类型定义 ======================== */
type SiteItem = {
    site_id: string | number
    site_name: string
    logo_s3?: string | null
    home_url: string
}

type ListQuery = {
    page: number
    pageSize: number
    keyword: string
}

/* ======================== 路由 ======================== */
const router = useRouter()

/* ======================== 状态 ======================== */
const loading = ref(false)
const inFlight = ref(false)
const deleting = ref(false)

const dataSource = ref<SiteItem[]>([])
const total = ref(0)
const allRows = ref<SiteItem[]>([])

const query = reactive<ListQuery>({
    page: 1,
    pageSize: 10,
    keyword: ''
})

/* ======================== 表格列 ======================== */
const columns = computed(() => [
    { title: '名称', dataIndex: 'site_name', key: 'site_name', ellipsis: true, width: 220 },
    { title: '图片', dataIndex: 'logo_s3', key: 'logo_s3', width: 120 },
    { title: '地址', dataIndex: 'home_url', key: 'home_url', ellipsis: true, width: 360 },
    { title: '操作', key: 'actions', fixed: 'right' as const, width: 160 }
])

/* ======================== 占位图 ======================== */
const fallbackImg =
    'data:image/svg+xml;charset=UTF-8,' +
    encodeURIComponent(
        `<svg xmlns="http://www.w3.org/2000/svg" width="80" height="48"><rect width="100%" height="100%" fill="#f5f5f5"/><text x="50%" y="50%" font-size="10" text-anchor="middle" fill="#aaa" dy=".3em">no image</text></svg>`
    )

/* ======================== 分页 + 关键词过滤 ======================== */
function refillTable() {
    const kw = query.keyword.trim().toLowerCase()
    const filtered = kw
        ? allRows.value.filter(
            (r) =>
                String(r.site_name || '').toLowerCase().includes(kw) ||
                String(r.home_url || '').toLowerCase().includes(kw)
        )
        : allRows.value

    total.value = filtered.length
    const start = (query.page - 1) * query.pageSize
    const end = start + query.pageSize
    dataSource.value = filtered.slice(start, end)
}

/* ======================== 获取列表 ======================== */
const fetchList = async () => {
    if (inFlight.value) return
    inFlight.value = true
    loading.value = true
    try {
        const payload: any = await (api as any).getWebsiteInfo()
        if (payload?.code !== 1000) throw new Error(payload?.message || '后端返回异常')

        const list: any[] = Array.isArray(payload?.data) ? payload.data : []
        allRows.value = list.map((it) => ({
            site_id: it.site_id,
            site_name: it.site_name,
            home_url: it.home_url,
            logo_s3: it.logo_s3
        }))

        refillTable()
    } catch (e: any) {
        message.error(e?.message || '获取列表失败')
    } finally {
        loading.value = false
        inFlight.value = false
    }
}

/* ======================== 跳转 ======================== */
const openCreate = () => {
    router.push({ name: 'sourceDataEdit' })
}
const openEdit = (row: SiteItem) => {
    router.push({ name: 'sourceDataEdit', params: { id: String(row.site_id) } })
}

/* ======================== 删除 ======================== */
const askDelete = (row: SiteItem) => {
    Modal.confirm({
        title: '删除确认',
        content: `确定要删除【${row.site_name || row.site_id}】吗？此操作不可恢复。`,
        okText: '删除',
        cancelText: '取消',
        okType: 'danger',
        maskClosable: false,
        centered: true,
        async onOk() {
            if (deleting.value) return
            deleting.value = true
            try {
                const resp: any = await (api as any).deleteWebsiteInfo({ site_id: row.site_id })
                if (resp?.code !== 1000) throw new Error(resp?.message || '删除失败')
                message.success('删除成功')

                // 删除后刷新
                const remain = Math.max(0, total.value - 1)
                const maxPage = Math.max(1, Math.ceil(remain / query.pageSize))
                if (query.page > maxPage) query.page = maxPage
                await fetchList()
            } catch (e: any) {
                message.error(e?.message || '删除失败')
                throw e
            } finally {
                deleting.value = false
            }
        }
    })
}

/* ======================== 分页与搜索 ======================== */
const handleSearch = () => {
    query.page = 1
    refillTable()
}
const onPageChange = (page: number) => {
    query.page = page
    refillTable()
}
const onPageSizeChange = (_: number, size: number) => {
    query.page = 1
    query.pageSize = size
    refillTable()
}


onMounted(() => {
    fetchList()
})
</script>

<style scoped lang="less">
.site-page {
    padding: 16px;
    min-height: 100%;
    box-sizing: border-box;

    /* 顶部工具条 */
    .page-header {
        margin-bottom: 12px;

        .toolbar {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;

            .search-input {
                width: 320px;
                max-width: 100%;
            }

            .btn {
                white-space: nowrap;
                border-radius: 10px;
            }
        }
    }

    .card {
        background: #fff;
        border-radius: 12px;
        padding: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, .06);
    }

    .site-table {

        :deep(.ant-table-thead > tr > th),
        :deep(.ant-table-tbody > tr > td) {
            height: 40px;
            padding: 10px 12px;
        }

        /* 图片 */
        .logo-box {
            width: 30px;
            height: 30px;
            border-radius: 6px;
            overflow: hidden;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: #fafafa;

            :deep(.ant-image) {
                width: 100%;
                height: 100%;
            }

            :deep(.ant-image-img) {
                width: 100%;
                height: 100%;
                object-fit: contain;
                display: block;
            }
        }

        /* 地址 */
        .url-text {
            display: inline-block;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: inherit;
        }

        /* 删除按钮 */
        .del-link {
            padding: 0;
        }
    }

    /* 分页靠右 */
    .table-footer {
        margin-top: 12px;
        display: flex;
        align-items: center;
        gap: 12px;
        flex-wrap: wrap;
        justify-content: flex-end;

        .total-text {
            color: #999;
            font-size: 13px;
        }
    }
}

/* 响应式*/
@media (max-width: 768px) {
    .site-page {
        .page-header .toolbar {
            .search-input {
                flex: 1;
                min-width: 200px;
                width: auto;
            }
        }

        .card {
            padding: 8px;
        }
    }
}

/* 超窄屏 */
@media (max-width: 480px) {
    .site-page {
        .site-table {
            :deep(.ant-table) {
                overflow-x: auto;
            }
        }
    }
}
</style>
